package com.BlogPark.controller;

import com.BlogPark.common.utis.CaptchaGenerator;
import com.BlogPark.common.utis.MD5Utils;
import com.BlogPark.common.utis.SendMail;
import com.BlogPark.controller.result.Result;
import com.BlogPark.mapper.DetailsUserMapper;
import com.BlogPark.pojo.User;
import com.BlogPark.service.BindMailboxService.BindMailboxService;
import com.BlogPark.service.LoginService.LoginService;
import com.BlogPark.service.RegistrationService.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;

import static com.BlogPark.controller.exception.Code.*;

/**
 * @Auther: MFM
 * @Date: 2022/8/10 - 08 - 10 - 22:09
 * @version: 1.0
 * 注册 响应
 */
@RestController
@RequestMapping("/user")
@Transactional
public class RegistrationController {

    @Autowired
    private RegistrationService registrationService;

    @Autowired
    private BindMailboxService bindMailboxService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private DetailsUserMapper detailsUserMapper;

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result Register(@RequestBody User user, HttpServletRequest request) {
        String queryString = request.getQueryString();
        String msg = registrationService.Register(user);

        if (msg.equals("注册成功")) {
            return new Result(SAVE_OK, msg);
        }
        return new Result(GET_ERR, msg);
    }


    /**
     * 邮箱注册链接
     *
     * @param request
     * @param email
     * @return
     */
    @GetMapping("/registerLink")
    public Result registerLink(HttpServletRequest request, @RequestParam("email") String email) {
        User usercheck = registrationService.findUserByEmail(email);
        System.out.println(usercheck);
        Result result = new Result();
        String msg = "";
        if (email.equals("")) {
            msg = "请输入邮箱！";
            result.setMsg(msg);
            result.setCode(GET_ERR);
        }
        if (usercheck != null) {         //用户已存在
            msg = "邮箱已存在,你这小可爱(tm)是不是忘了了?!，请点击'找回密码'";
            result.setCode(GET_ERR);
            result.setMsg(msg);
        } else {
            try {
                User user = new User();
                String pwd = CaptchaGenerator.generatorPwdAndUser(8);
                String mdpwd = MD5Utils.getMd5(pwd);
                user.setPassword(mdpwd);
                user.setUsername(email);
                user.setEmail(email);
                bindMailboxService.bindMail(user); //保存到数据库
                user = registrationService.findUserByEmail(email);
                String secretKey = UUID.randomUUID().toString();  //密钥
                Timestamp outDate = new Timestamp(System.currentTimeMillis() + 5 * 60 * 1000);//5分钟后过期
                long date = outDate.getTime() / 1000 * 1000;                  //忽略毫秒数
                user.setValidatacode(secretKey);
                user.setOutdate(outDate);
                bindMailboxService.updateCodeAndDate(user);
                String key = user.getEmail() + "$" + date + "$" + secretKey;
                String digitalSignature = MD5Utils.getMd5(key);                 //数字签名
                String localstr = request.getLocalAddr();
                System.out.println(localstr);
                String basePath = request.getScheme() + "://" +"120.53.246.47:3002/01BlogPark-1.0-SNAPSHOT" +"/";
                String registerPassHref = basePath + "user/registerUser?sid=" + digitalSignature + "&email=" + user.getEmail();

                String emailContent = "请勿回复本邮件.账户已激活<br/>"+
                        "请使用您的邮箱登录"+"\n"+"默认密码为："+pwd+"\n"+"请尽快修改密码，谢谢"+
                        "<br/>01Blog欢迎您！" ;
                //发送
                SendMail sendMail = new SendMail();
                //初始化用户详情
                detailsUserMapper.defaultDetailInfo(user.getId());
                //激活账户
                bindMailboxService.doActivCode(email);
                sendMail.sendMail(user.getEmail(), emailContent);
                msg = "操作成功,已经发送注册链接到您邮箱,请查收";

            } catch (Exception e) {
                e.printStackTrace();
                msg = "请检查邮箱是否存在";
            }
        }
        result.setMsg(msg);
        result.setCode(GET_OK);
        result.setData("true");
        return result;
    }


    /**
     * 解析链接
     *
     * @param sid
     * @param email
     * @return
     */
    @GetMapping("/registerUser")
    public String checkRegisterLink(@RequestParam("sid") String sid, @RequestParam("email") String email) {
        System.out.println("sid:" + sid + "\n" + "email:" + email);
        String msg = "";
        String t = "";
        if (sid.equals("") || email.equals("")) {
            msg = "链接不完整,请重新生成";
        }

        User user = loginService.findUserByEmail(email);
        if (user == null) {
            msg = "链接错误,请重新申请注册";
        }
        Date outDate = user.getOutdate();
        if (outDate.getTime() <= System.currentTimeMillis()) {         //表示已经过期
            msg = "链接已经过期,请重新申请找回密码.";
        }
        String key = user.getEmail() + "$" + outDate.getTime() / 1000 * 1000 + "$" + user.getValidatacode();          //数字签名
        String digitalSignature = MD5Utils.getMd5(key);
        System.out.println(key + "\t" + digitalSignature);
        if (!digitalSignature.equals(sid)) {
            msg = "链接不正确,是否已经过期了?重新申请吧";
        } else {
            //初始化用户详情
            detailsUserMapper.defaultDetailInfo(user.getId());
            bindMailboxService.doActivCode(email);
            msg= "success! please back to login!";
        }
        return msg;
    }

}
